package com.cljh.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.cljh.bean.Product;
import com.cljh.bean.Products;
import com.cljh.config.AuthAccess;
import com.cljh.controller.page.*;
import com.cljh.service.ProductService;
import com.cljh.service.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物清单控制器
 */
@RestController
@RequestMapping("/user_products")
public class ProductsController {

    @Autowired
    ProductsService productsService;

    @AuthAccess
    @PostMapping("/{pn}/{size}")
    public Result selectProducts(@PathVariable(value = "pn") Integer pn, @PathVariable(value = "size") Integer size, @RequestBody UserPageBean userPageBean) {
        PageBean<UserPageBean> userPageBeanPageBean = productsService.productsConditionList(pn, size, userPageBean);
        Integer code = userPageBeanPageBean != null ? Code.GET_OK : Code.GET_ERR;
        String msg = userPageBeanPageBean != null ? "查询到信息" : "未查询到信息";
        return new Result(code, userPageBeanPageBean, msg);
    }


    @PostMapping
    public Result save(@RequestBody Products products) {

        boolean save = productsService.save(products);
        Integer code=save ? Code.SAVE_OK:Code.SAVE_ERR;
        String msg=save ? "添加成功":"添加失败";
        return new Result(code,save,msg);
    }

    @DeleteMapping("/{id}")
    public Result delete( @PathVariable Integer id) {
        boolean delete = productsService.delete(id);
        Integer code=delete ? Code.DELETE_OK:Code.DELETE_ERR;
        String msg=delete ? "删除一个成功":"删除一个失败";
        return new Result(code,delete,msg);
    }


    @PutMapping
    public Result update(@RequestBody UserPageBean products) {
        Integer id = products.getId();
        Integer userId = products.getUserId();
        Integer productId = products.getProductId();
        Long productSum = products.getSum();
        Products products1 = new Products();
        products1.setId(id);
        products1.setUserId(userId);
        products1.setProductId(productId);
        products1.setSum(productSum);

        boolean update = productsService.update(products1);
        Integer code=update ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg=update ? "修改成功":"修改失败";
        return new Result(code,update,msg);
    }


    @DeleteMapping("/deleteIds")
    public Result deleteByIds(@RequestBody List<Integer> ids) {
        boolean b = productsService.deleteByIds(ids);
        Integer code=b ? Code.DELETE_OK:Code.DELETE_ERR;
        String msg=b ? "删除成功":"删除失败";
        return new Result(code,b,msg);
    }


    /**
     * id查询
     * @param id
     * @return
     */
    @AuthAccess
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        UserPageBean userPageBean = productsService.selectById(id);
        Integer code=userPageBean !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=userPageBean!=null ? "查询到信息":"未查询到信息";
        return new Result(code,userPageBean,msg);
    }


    /**
     * 导出excel表格
     * @param response
     * @throws Exception
     */

    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        List<ProductList> list = productsService.productsList();
        ExcelWriter writer= ExcelUtil.getWriter(true);

        writer.addHeaderAlias("id" ,"id");
        writer.addHeaderAlias("name" ,"姓名");
        writer.addHeaderAlias("gender" ,"性别");
        writer.addHeaderAlias("productName" ,"商品名称");
        writer.addHeaderAlias("price" ,"价格");
        writer.addHeaderAlias("types" ,"款式");
        writer.addHeaderAlias("productSize" ,"尺码");
        writer.addHeaderAlias("productColor" ,"商品颜色");
        writer.addHeaderAlias("productMaterials" ,"商品材质");
        writer.addHeaderAlias("sum" ,"商品个数");

        writer.write(list,true);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName= URLEncoder.encode("商品信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        ServletOutputStream out =response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    @Autowired
    ProductService productService;
    @GetMapping("/user/{userId}")
    public Result selectUser(@PathVariable Integer userId){
        List<Products> products = productsService.selectByUser(userId);
        List<ProductPageBean> list = new ArrayList<>();
        for (Products p :
                products) {

            Integer productId = p.getProductId();
            ProductPageBean pageBean = productService.selectById(productId);
            pageBean.setProductsId(p.getId());
            pageBean.setProductSum(p.getSum());
            list.add(pageBean);
        }
        PageBean<ProductPageBean> userPageBeanPageBean = new PageBean<>();
        userPageBeanPageBean.setRows(list);
        userPageBeanPageBean.setTotalCount(list.size());
        Integer code=userPageBeanPageBean !=null ? Code.GET_OK:Code.GET_ERR;
        String msg=userPageBeanPageBean!=null ? "查询到信息":"未查询到信息";
        return new Result(code,userPageBeanPageBean,msg);
    }

    @Transactional(rollbackFor = Exception.class)
    @PutMapping("/user")
    public Result updProducts(@RequestBody List<ProductPageBean> products){
        System.out.println(products);
        for (ProductPageBean p : products) {
            Products products1 = new Products();
            products1.setSum(Long.valueOf(p.getProductSum()));
            products1.setId(p.getProductsId());
            productsService.update(products1);
        }
        return new Result(Code.UPDATE_OK,true,"修改成功");
    }
    @DeleteMapping("/user/{userId}")
    public Result selectId(@RequestBody List<Integer> productIds, @PathVariable Integer userId){
        System.out.println(productIds);
        System.out.println(userId);
        return new Result();
    }
}
